package com.geeka.d12.work.chatroom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.*;

public class TcpServerWithPoolChatRoom {

    public static ArrayList<Socket> sockets= new ArrayList<>();
    String welcomeMsg = "欢迎进入聊天室...";
    // 创建线程池
    private static ExecutorService threadPool = new ThreadPoolExecutor(10, 30, 20, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());


    public static void main(String[] args) {
        int port = 9999;

        try (ServerSocket serverSocket = new ServerSocket(port);) {
            System.out.println("服务器已启动，端口号：" + port);


            while (true) {
                // 阻塞等待client的连接
                Socket socket = serverSocket.accept();
                System.out.println("sockets: " + sockets);
                sockets.add(socket);
                String cname = socket.getInetAddress() + " 端口:" + socket.getPort();
                System.out.println("有客户端连接上了服务器: " + cname );
                // 利用线程池来配陪同者
                threadPool.execute(new SocketTask(sockets,socket)); // 给线程传入当前socket 及sockets集合
            }
        } catch (IOException e) {
            System.out.println("发生异常" + e.getMessage());
            e.printStackTrace();
        }
    }
}
